package com.siblings.loan.analysis.util

import android.app.Activity
import android.app.Application
import android.os.Bundle
import com.adjust.sdk.Adjust
import com.adjust.sdk.AdjustAttribution
import com.adjust.sdk.AdjustConfig
import com.adjust.sdk.AdjustEvent
import com.adjust.sdk.LogLevel
import com.siblings.loan.analysis.AnalysisBuilder
import com.siblings.loan.analysis.bean.AdjustInstallBean
import com.siblings.loan.analysis.event.IAnalyticsEvent
import com.siblings.loan.analysis.http.HttpHelper
import com.siblings.loan.analysis.http.UrlHelper
import com.siblings.loan.config.SibConfigs

object AdjustUtil {

    /** adjust env */
    private const val AJ_ENVIRONMENT = AdjustConfig.ENVIRONMENT_PRODUCTION

    /** adjust token */
    private const val AJ_TOKEN = SibConfigs.SIB_ADJ_TOKEN // TODO: 填写对应的值

    /** adjust 注册事件码 */
    private const val AJ_EVENT_REGISTER = SibConfigs.SIB_ADJ_EVENT_REGISTER // TODO: 填写对应的值

    /** adjust 申请事件码 */
    private const val AJ_EVENT_APPLY = SibConfigs.SIB_ADJ_EVENT_APPLY // TODO: 填写对应的值

    /** 归因信息 */
    private var _adjsutAttribution: AdjustInstallBean? = null

    /**
     * 初始化Adjust模块
     * 按配置需要来初始化
     *
     * @param context Application
     */
    fun init(context: Application) {
        // 按需要判断，3个key值不能为空
        if (AJ_TOKEN.isBlank()) throw Exception("Error: Adjust Token must no be null!")
        if (AJ_EVENT_REGISTER.isBlank()) throw Exception("Error: Adjust Register code must no be null!")
        if (AJ_EVENT_APPLY.isBlank()) throw Exception("Error: Adjust Apply code must no be null!")

        if (AnalysisBuilder.zone.isBlank()) return

        val config = AdjustConfig(context, AJ_TOKEN, AJ_ENVIRONMENT)
        config.setLogLevel(LogLevel.INFO)
        config.setOnAttributionChangedListener { saveAttribution(it) }
        Adjust.onCreate(config)

        registerAdjustActivityLifecycle(context)

        val attribution = Adjust.getAttribution()
        saveAttribution(attribution)
    }

    private fun saveAttribution(attribution: AdjustAttribution?) {
        attribution?.let { result ->
            _adjsutAttribution = AdjustInstallBean()
            _adjsutAttribution?.let { params ->
                params.adid = result.adid.orEmpty()
                params.network = result.network.orEmpty()
                params.adgroup = result.adgroup.orEmpty()
                params.creative = result.creative.orEmpty()
                params.costType = result.costType.orEmpty()
                params.campaign = result.campaign.orEmpty()
                params.clickLabel = result.clickLabel.orEmpty()
                params.trackerName = result.trackerName.orEmpty()
                params.trackerToken = result.trackerToken.orEmpty()
                params.costCurrency = result.costCurrency.orEmpty()
                params.fbInstallReferrer = result.fbInstallReferrer.orEmpty()
                result.costAmount?.let { costAmount ->
                    params.costAmount = costAmount.toString()
                }

                //上报
                println("=====adjust attribution finish")
                saveInstallInfo()
            }
        }
    }

    fun addEvent(event: IAnalyticsEvent) {
        try {
            when (event) {
                IAnalyticsEvent.AT_REGISTER -> {
                    Adjust.trackEvent(AdjustEvent(AJ_EVENT_REGISTER))
                }

                IAnalyticsEvent.AT_LOAN_APPLY -> {
                    Adjust.trackEvent(AdjustEvent(AJ_EVENT_APPLY))
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun saveInstallInfo() {
        try {
            _adjsutAttribution?.let { data ->
                val url = UrlHelper.combineUrl()
                val path = AnalysisBuilder.pathAdjustInstall
                val body = data.encrypt(path)
                HttpHelper.postData(url, body)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun registerAdjustActivityLifecycle(context: Application) {
        context.registerActivityLifecycleCallbacks(object : Application.ActivityLifecycleCallbacks {
            override fun onActivityCreated(p0: Activity, p1: Bundle?) {
            }

            override fun onActivityStarted(p0: Activity) {
            }

            override fun onActivityResumed(p0: Activity) {
                Adjust.onResume()
            }

            override fun onActivityPaused(p0: Activity) {
                Adjust.onPause()
            }

            override fun onActivityStopped(p0: Activity) {
            }

            override fun onActivitySaveInstanceState(p0: Activity, p1: Bundle) {
            }

            override fun onActivityDestroyed(p0: Activity) {
            }
        })
    }
}